if (document.images) {

    var expand = new Image();
    expand.src = "public/img/expand.png";
  
    var collapse = new Image();
    collapse.src = "public/img/collapse.png";
    
    var expandH = new Image();
    expandH.src = "public/img/expand-h.png";
  
    var collapseH = new Image();
    collapseH.src = "public/img/collapse-h.png";
    
    
}

// fonction permettant de changer les images d'un projet
function changeImg(){
    document.images.logo.src="public/img/thumbs/"+$("#ddlProjects option:selected")[0].text+".png";
    document.images.logo.onerror = function () { 
        this.src = "public/img/logo.png";
    }
}
// Les fonctions ci dessous se chargent au lancement de la page web
$(document).ready(function() {
    $('.dropdown-toggle').dropdown();
    var url = window.location.search;;
    
    var errorDialogOptions = {
            title: "Informations : Erreur",
            modal: true,
            autoOpen: true,
            buttons: {
                "Fermer": function(){
                    $(this).dialog("close");
                }
                
            },
            width: 550
            
        };
    if (url.indexOf("error") != -1)
        $("#error-dialog").dialog(errorDialogOptions);

    // Création du tableau qui va contenir tous les graphiques
	var charts = new Array();
	var lastServiceId = null, serviceDataDetail = null;
	// Ajout d'un graphique par défaut
    charts.push(showChart());
	
    // Création de la liste délourante pour sélectionner les cartes à afficher
	$('.ddlCards').multiselect({
		minWidth: 160,
		checkAllText: 'tout cocher',
		uncheckAllText: 'tout d&eacute;cocher',
		noneSelectedText: 'cartes :',
		selectedText: "# carte(s)"
	});
	
	$('.ddlCards').multiselect('checkAll');
	
    changeImg();
    
    // Affichage des données d'une colonne lors du clic sur celle-ci
    $('.cbxChartColumns').live('click', function() {
    	var chartNumber = getChartNumber($(this));
    	var chart = charts[chartNumber];
    	var selectedCards = $('#ddlCards_' + chartNumber).val();
    	var labels = new Array();
    	
    	if(selectedCards != null) {
    		var columnName = $(this).val();
    		var series = new Array();
    		var alreadyLoaded = false, hasServicesData = false;
    		
    		// Check if data have already been loaded
    		$('#chart_' + chartNumber + ' .jqplot-table-legend-label').each(function() {
    			labels.push($(this).text());
    			
    			if($(this).text().indexOf('- ' + columnName) != -1) {
    				series.push($(this));
    				alreadyLoaded = true;
    			}
    		});
    		
    		var httpRequest = 'project=' + $("#ddlProjects").val() + '&servicesData=' + $('#param-graphe_' + chartNumber + ' .cbxServicesData').is(':checked') + '&cards[]=' + selectedCards;
    		
    		if(columnName != 'services_data') {
    			httpRequest += '&column=' + columnName;
    		}
    		
    		// Otherwise, get data in database with AJAX call
    		if(!alreadyLoaded && $(this).is(':checked')) {
    			$.ajax({
    				type: 'GET',
    				data: httpRequest,
    				url: 'Ajax.php',
    				dataType: 'json',
    				success:function(json) {
    					var min = null, max = null;
    					
    					// Empty the div in order to create a new chart
    					$('#chart_' + chartNumber).empty();
    					
    					// If data are empty
    					if(chart.data[0][0] == null) {
    						chart.options = getCurrentChartTypeOptions(chartNumber);
    						chart.options.series = new Array();
    					}
    					
    					for(var i in json) {
    						if(i != 'services_data') {
    							if(chart.data[0][0] == null)
        							chart.data[0] = json[i];
        						else
        							chart.data.push(json[i]);
    							
        						chart.options.series.push(new Array());
        						chart.options.series[chart.options.series.length - 1].label = i + ' - ' + columnName;
    						}
    						else {
    							// Get services data from json
    							if(chart.data[0][0] != null) {
    								var serviceDataId = null;
	    							hasServicesData = true;
	    							
    								// Search min and max in order to draw a line on the chart for services data
        							if(min == null || max == null) {
        								for(var j in chart.data) {
            								for(var k in chart.data[j]) {
            									if(max < chart.data[j][k][1] || max == null) {
                        							max = chart.data[j][k][1];
                    							}
                        						
                        						if(min > chart.data[j][k][1] || min == null) {
                        							min = chart.data[j][k][1];
                        						}
            								}
                						}
        							}
    							}
    							
    							// Valeur par défaut
    							if(min == null || max == null) {
    								min = 0;
    								max = 50;
    							}
    							
    							for(var j in json[i]) {
    								for(k in json[i][j]) {
    									// Si la donnée est une donnée de service
	    								if(json[i][j][k][0] == 'id_services_data') {
	    									serviceDataId = json[i][j][k][1];
	    								}
	    								
	    								// Si la donnée est une date
	    								if(json[i][j][k][0] == 'date') {
	    									// On vérifie que la série n'a pas déjà été chargée
	    									if(!serieAlreadyLoaded(labels, serviceDataId)) {
	    										if(chart.data[0][0] == null)
	    		        							chart.data[0] = [[json[i][j][k][1], min], [json[i][j][k][1], max]];
	    		        						else
	    		        							chart.data.push([[json[i][j][k][1], min], [json[i][j][k][1], max]]);
	    										
	    									}
	    								}
    								}
    								
            						chart.options.series.push(new Array());
            						chart.options.series[chart.options.series.length - 1].label = serviceDataId + ' - ' + i;
    							}
    						}
    					}
    					
    					chart = $.jqplot('chart_' + chartNumber, chart.data, chart.options);
    				}
    			});
    		}
    		// Toggle the selected serie
    		else {
    			for(var i = 0; i < series.length; i++) {
    				$(series[i]).trigger('click', ['speed:900']);
    			}
    		}
    	}
    });
    
    // Reset du graphique
    $('.resetChart').live('click', function() {
    	var chartNumber = getChartNumber($(this));
    	$('#chart_' + chartNumber).empty();
    	charts[chartNumber] = showChart(chartNumber);
    	$('#param-graphe_' + chartNumber + ' .cbxChartColumns').removeAttr('checked');
    });
    
    // Permet de filtrer les données sur une période
    $(".bt-filter").live('click', function(e){
    	var chartNumber = getChartNumber($(this));
        var columnNames = new Array();
        var series = new Array();
        var startDate = $("#date-start_" + chartNumber).val().replace(' ', '').replace('-','').replace('-','').replace(':','').replace(':',''); 
        var endDate = $("#date-end_" + chartNumber).val().replace(' ', '').replace("-","").replace('-','').replace(':','').replace(':','');
        
        // On récupère toutes les colonnes cochées
        $('#param-graphe_' + chartNumber + ' .cbxChartColumns:checked').each(function() {
        	if($(this).val() != 'services_data') {
            	columnNames.push($(this).val());
        	}
        });
        
        $.ajax({
            type: 'GET',
            data: 'project=' + $("#ddlProjects").val() + '&columns[]=' + columnNames.toString() + '&cards[]=' + $('#ddlCards_' + chartNumber).val() + '&servicesData=' + $('#param-graphe_' + chartNumber + ' .cbxServicesData').is(':checked') + '&ds=' + startDate + '&de=' + endDate,
            url: 'Ajax.php',
            dataType: 'json',
            success:function(json) {
				var min = null, max = null;
				
				if(json == null || json == '') {
                	return;
                }
				
                $('#chart_' + chartNumber).empty();
                chart = charts[chartNumber];

                chart.data.length = 0;
                chart.data.push(new Array());
                
                if(chart.data[0][0] == null) {
					chart.options = getCurrentChartTypeOptions(chartNumber);

	                chart.options.series = new Array();
				}
                
                // Récupération des données en JSON
                for(var i in json) {
                	// Si ce n'est pas des données de service
					if(i != 'services_data') {
	                	for(var j in json[i]) {
								if(chart.data[0][0] == null)
									chart.data[0] = json[i][j];
								else
									chart.data.push(json[i][j]);
	                		
	                		chart.options.series.push(new Array());
							chart.options.series[chart.options.series.length - 1].label = i + ' - ' + j;
	                	}
					}
					else {
						// Get services data from json
						if(chart.data[0][0] != null) {
							var serviceDataId = null;
							hasServicesData = true;
							
							// Search min and max in order to draw a line on the chart for services data
							if(min == null || max == null) {
								for(var j in chart.data) {
    								for(var k in chart.data[j]) {
    									if(max < chart.data[j][k][1] || max == null) {
                							max = chart.data[j][k][1];
            							}
                						
                						if(min > chart.data[j][k][1] || min == null) {
                							min = chart.data[j][k][1];
                						}
    								}
        						}
							}
						}
						
						// Valeur par défaut
						if(min == null || max == null) {
							min = 0;
							max = 50;
						}
						
						for(var j in json[i]) {
							for(k in json[i][j]) {
								// Si la donnée est une donnée de service
								if(json[i][j][k][0] == 'id_services_data') {
									serviceDataId = json[i][j][k][1];
								}
								// Si la donnée est une date
								if(json[i][j][k][0] == 'date') {
									if(chart.data[0][0] == null)
	        							chart.data[0] = [[json[i][j][k][1], min], [json[i][j][k][1], max]];
	        						else
	        							chart.data.push([[json[i][j][k][1], min], [json[i][j][k][1], max]]);
								}
							}
							
    						chart.options.series.push(new Array());
    						chart.options.series[chart.options.series.length - 1].label = serviceDataId + ' - ' + i;
						}
					}
				}
                
            	chart = $.jqplot('chart_' + chartNumber, chart.data, chart.options);
            }
        });
    });
	
    // Pop-up d'ajout des données du graphe et des données de service
    $('#button-add').live('click', function(e) {
          
        var dialogOpts = {
            title: "Ajouter un fichier",
            modal: true,
            autoOpen: false,
            buttons: {
                
               
                "Annuler": function(){
                    $(this).dialog("close");
                },
                "Ajouter": function(){
                    $("#form-add-csv").submit();
                }
                
            },
            width: 550
            
        };
        
        $("#dialog-add").dialog(dialogOpts);    //end dialog
    
        $("#dialog-add").dialog("open");
        return false;
    });
    
    // Affiche les options sur le coté du graphe
    $('.expand-h').live('click', function() {
    	var chartNumber = getChartNumber($(this));
    	var chart = charts[chartNumber];
        if($('#chart_container_' + chartNumber).css("width") == "980px")
        {
            $('#chart_container_' + chartNumber).css('width', '80%')
            $("#param-graphe_" + chartNumber).toggle();
            $("#param-date_" + chartNumber).show();
            document["expand-h_" + chartNumber].src = collapseH.src;
        }
        else
        {
            $("#param-graphe_" + chartNumber).toggle(); 
            $('#chart_container_' + chartNumber).css('width', '100%');
            $("#param-date_" + chartNumber).hide();
            document["expand-h_" + chartNumber].src = expandH.src
        }

        $('#chart_' + chartNumber).empty();
        chart = $.jqplot('chart_' + chartNumber, chart.data, chart.options);
    });
    
    // Lorsqu'un type de graphe est sélectionné
    $('.chartType input:radio').live('change', function() {
    	var chartNumber = getChartNumber($(this));
    	var chart = charts[chartNumber];
    	var options = null;
    	
        if(chart.data[0][0] != null) {
            $('#chart_' + chartNumber).empty();
            var options = getCurrentChartTypeOptions(chartNumber);
            options.series = chart.options.series;
            
            for(var i = 0; i < options.series.length; i++) {
            	var label = options.series[i].label;
            	
            	// Show line for services data
            	if(label.indexOf('services_data') > 0) {
            		options.series[i] = new Array();
            		options.series[i].label = label;
            		options.series[i].showLine = true;
            	}
            }
            
            charts[chartNumber] = $.jqplot('chart_' + chartNumber, chart.data, options);
            $('chart_' + chartNumber).CanvasHack();
        }
    });
    
    // Affichage du nom d'un projet
    $("#title-project").html($("#ddlProjects option:selected").text());
    
    $("#ddlProjects").change(function() {
        window.location = "main.php?page=0&project=" + $("#ddlProjects option:selected").val();
        document.images.logo.src="public/img/"+$("#ddlProjects option:selected")[0].text+".png";
        
    });
    
    // Affichage de la pop-up pour sélectionner une date
    $('.date-end, .date-start').live('focus', function() {
    	$('.date-end, .date-start').datetimepicker({
            dateFormat:'dd-mm-yy', 
            showSecond:true, 
            timeFormat: 'hh:mm:ss'
        });
    });
    
    // Toolbar
    
    // Affichage du graphique en image dans une pop-up
    $('.ui-icon-image').live('click', function() {
    	var chart = $('#chart_' + getChartNumber($(this)));
        var imgelem = chart.jqplotToImageElem();
        var div = $('div.overlay-chart-container-content');
        div.empty();
        div.append(imgelem);
        $('div.overlay-shadow').fadeIn(600);
        div.parent().fadeIn(1000);
        div = null;
    });
    
    // Fermeture de la pop-up qui affiche l'image du graphique
    $('.ui-icon-closethick').live('click', function(){
        $('div.overlay-chart-container-content').parent().fadeOut(600);
        $('div.overlay-shadow').fadeOut(1000);
    });
    
    // Impression du graphique
    $('.ui-icon-print').live('click', function(){
        $(this).parent().print();
    });
    
    // Ajout d'un nouveau graphique
    $('.addChart').live('click', function() {
    	var chartNumber = parseInt($('.chart_wrap').last().find('.chartNumber').val()) + 1;
    	var selectedValue = $('#page-content').find('#chartType_' + (chartNumber - 1)).find(':radio:checked').val();
    	$('#page-content').append($('.chart_wrap').last().clone());
    	
    	var chart_wrap = $('.chart_wrap').last();
    	chart_wrap.attr('style', 'margin-top:70px');
    	chart_wrap.find('.chartNumber').val(chartNumber);
    	chart_wrap.find('#chart_' + (chartNumber - 1)).attr('id', 'chart_' + chartNumber);
    	chart_wrap.find('#date-start_' + (chartNumber - 1)).attr('id', 'date-start_' + chartNumber);
    	chart_wrap.find('#date-end_' + (chartNumber - 1)).attr('id', 'date-end_' + chartNumber);
    	chart_wrap.find('#param-graphe_' + (chartNumber - 1)).attr('id', 'param-graphe_' + chartNumber);
    	chart_wrap.find('#param-date_' + (chartNumber - 1)).attr('id', 'param-date_' + chartNumber);
    	chart_wrap.find('#chart_container_' + (chartNumber - 1)).attr('id', 'chart_container_' + chartNumber);
    	chart_wrap.find('.ddlCards').attr('id', 'ddlCards_' + chartNumber);
    	chart_wrap.find('#expand-h_' + (chartNumber - 1)).attr('id', 'expand-h_' + chartNumber);
    	chart_wrap.find('#chartType_' + (chartNumber - 1)).attr('id', 'chartType_' + chartNumber);
    	chart_wrap.find('#chartType_' + chartNumber).find(':radio').each(function() {
    		$(this).attr('name', 'chartType_' + chartNumber);
    	});
    	chart_wrap.find('#param-graphe_' + chartNumber + ' .cbxChartColumns:checkbox').attr('checked', false);
    	$('#chartType_' + (chartNumber - 1) + ' input[value="' + selectedValue + '"]').attr('checked', true);
    	
    	// Destroy the multiselect plugin in order to refresh it
    	chart_wrap.find('.ui-multiselect').remove();
    	$('#chart_' + chartNumber).empty();
    	charts.push(showChart(chartNumber));

    	chart_wrap.find('#ddlCards_' + chartNumber).multiselect({
    		minWidth: 160,
    		checkAllText: 'tout cocher',
    		uncheckAllText: 'tout d&eacute;cocher',
    		noneSelectedText: 'cartes :',
    		selectedText: "# carte(s)"
    	});
    	
    	chart_wrap.find('#ddlCards_' + chartNumber).multiselect('checkAll');
    });
    
    // Affichage/masquage du graphique
    $('.chart-toggle').live('click', function() {
    	var chartNumber = getChartNumber($(this));
    	chart = charts[chartNumber];
    	
    	// On masque le graphe
        if ($(this).hasClass('ui-icon-arrowthickstop-1-n')) {
        	$("#param-graphe_" + chartNumber).hide(); 
            $('#chart_container_' + chartNumber).css('width', '100%');
        	$("#chart_container_" + chartNumber).parent().attr('style', 'height:0px;');
            $("#param-date_" + chartNumber).hide();
            $("#expand-h_" + chartNumber).hide();
            
            $(this).parent().next().effect('blind', {mode:'hide'}, 600);
            $(this).removeClass('ui-icon-arrowthickstop-1-n');
            $(this).addClass('ui-icon-arrowthickstop-1-s');
        }
        // On affiche le graphe
        else if ($(this).hasClass('ui-icon-arrowthickstop-1-s')) {
        	$("#chart_container_" + chartNumber).parent().attr('style', 'height:450px;');
            $("#expand-h_" + chartNumber).show();
            $(this).parent().next().effect('blind', {mode:'show'}, 600);
            $(this).removeClass('ui-icon-arrowthickstop-1-s');
            $(this).addClass('ui-icon-arrowthickstop-1-n');
        }
        
        $('#chart_' + chartNumber).empty();
        chart = $.jqplot('chart_' + chartNumber, chart.data, chart.options);
    });
    
    // Affichage du détail des données de service au survol du point sur le graphique
    $('.chart').live('jqplotDataMouseOver', function (ev, seriesIndex, pointIndex, data, radius) {
    	var chartNumber = getChartNumber($(this));
    	var label = charts[chartNumber].options.series[seriesIndex].label;
    	
    	if(label.indexOf('services_data') > 0) {
	    	var id = label.substr(0, label.indexOf(' '));
	    	
	    	var tooltip = $(this).find('.jqplot-highlighter-tooltip');
	    	tooltip.empty();
	    	tooltip.css('width', '150px');
	    	
	    	if(id != lastServiceId) {
	    		lastServiceId = id;
	    		serviceDataDetail = '';
	    		$.ajax({
	                type: 'GET',
	                data: 'servicesId=' + id,
	                url: 'Ajax.php',
	                dataType: 'json',
	                success:function(json) {
	                	for(i in json) {
	                		for(j in json[i]) {
	                			serviceDataDetail += j + ' : ' + json[i][j] + '<br />';
	                		}
	                	}
	                }
	        	});
	    	}
	    	
	    	tooltip.html(serviceDataDetail);
    	}
	});
});

(function($) {
    $.fn.CanvasHack = function() {
        var canvases = this.find('canvas').filter(function() {
            return $(this).css('position') == 'absolute';
        });

        canvases.wrap(function() {
            var canvas = $(this);
            var div = $('<div />').css({
                position: 'absolute',
                top: canvas.css('top'),
                left: canvas.css('left')
            });
            canvas.css({
                top: '0',
                left: '0'
            });
            return div;
        });

        return this;
    };
})(jQuery);

function getChartNumber(element) {
	return parseInt(element.parents('.chart_wrap').find('.chartNumber').val());
}

// Fonction qui permet de vérifier qu'une série n'a pas été déjà chargée
function serieAlreadyLoaded(labels, id) {
	for(var index in labels) {
		var labelId = labels[index].substr(0, labels[index].indexOf(' '));
		
		if(labels[index].indexOf('services_data') > 0 && labelId == id) {
			return true;
		}
	}
	
	return false;
}

jQuery(function($){
	$.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
		closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
		prevText: '<Préc', prevStatus: 'Voir le mois précédent',
		nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
		currentText: 'Courant', currentStatus: 'Voir le mois courant',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
		'Jul','Aoû','Sep','Oct','Nov','Déc'],
		monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
		weekHeader: 'Sm', weekStatus: '',
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
		dateFormat: 'dd/mm/yy', firstDay: 0, 
		initStatus: 'Choisir la date', isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
        
        $.timepicker.regional['fr'] = {
	timeOnlyTitle: 'Choisir l\'heure',
	timeText: 'Temps',
	hourText: 'Heure',
	minuteText: 'Minute',
	secondText: 'Seconde',
	millisecText: 'Milli-seconde',
	currentText: 'Maintenant',
	closeText: 'Fermer',
	ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['fr']);
});